import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter, constantRoutes, allAsyncRoutes, anyRoute } from '@/router'
import router from "@/router"
import cloneDeep from "lodash/cloneDeep"

const state = {
  token: getToken(),
  name: "",
  avatar: "",
  buttons: [],
  roles: [],
  asycnRoutes: [],
  routes: [],
}

const mutations = {
  RESET_STATE: (state) => {
    state.token = "";
    state.name = "";
    state.avatar = "";
    state.buttons = [];
    state.roles = [];
    state.asycnRoutes = [];
    state.routes = [];
    // Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO(state, userInfo) {
    state.name = userInfo.name;
    state.avatar = userInfo.avatar;
    state.buttons = userInfo.buttons;
    state.roles = userInfo.roles;
  },
  SET_ASYNCROUTES(state, asyncRoutes) {
    state.asyncRoutes = asyncRoutes
    state.routes = constantRoutes.concat([...asyncRoutes, anyRoute])
    router.addRoutes(asyncRoutes, anyRoute)
  }
}

const actions = {
  // user login
  async login({ commit }, userInfo) {
    try {
      const result = await login({ username: userInfo.username.trim(), password: userInfo.password })
      let { code, data } = result;
      if (code === 200 || code === 20000) {
        commit('SET_TOKEN', data.token)
        setToken(data.token)
      }
    } catch (error) {

    }
  },

  // get user info
  async getInfo({ commit, state }) {
    try {
      const result = await getInfo(state.token);
      if (result.code === 200 || result.code === 20000) {
        const { data } = result
        if (!data) {
          return new Promise.reject(new Error("Verification failed, please Login again."))
        }
        commit('SET_USERINFO', data)
        commit("SET_ASYNCROUTES", filterUserAsyncRoutes(cloneDeep(allAsyncRoutes), data.routes))
      }
    } catch (error) {

    }
  },

  // user logout
  async logout({ commit, state }) {
    try {
      const result = await logout(state.token);
      let { code } = result;
      if (code === 200 || code === 20000) {
        removeToken();
        resetRouter();
        commit('RESET_STATE')
      }
    } catch (error) {

    }
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

function filterUserAsyncRoutes(allAsyncRoutes, routesNames) {
  return allAsyncRoutes.filter(item => {
    if (routesNames.indexOf(item.name) !== -1) {
      if (item.children && item.children.length) {
        item.children = filterUserAsyncRoutes(item.children, routesNames)
      }
      return true
    }
  })
}

